<?php
namespace Service\Library;

use \Service\Library\LibCommon;
use \Service\Library\LibConfig;

/**
 * Redis instance
 */
class LibRedis
{
    /**
     * Self instance
     * @var array
     */
    private static $ins = [];

    /**
     * Redis object
     * @var object
     */
    private $redis;

    /**
     * redis connect host
     * @var string
     */
    private $host;

    /**
     * redis connect port
     * @var integer
     */
    private $port;

    /**
     * redis connect auth
     * @var string
     */
    private $auth;

    /**
     * redis connect db
     * @var integer
     */
    private $select;

    /**
     * redis connect type (pconnect or connect)
     * @var string
     */
    private $conn_type;

    /**
     * Single instance
     * @param string $ins_name
     * @return object
     */
    public static function getIns($ins_name = 'default')
    {
        if(empty(self::$ins[$ins_name])) {
            self::$ins[$ins_name] = new self($ins_name);
        }

        return self::$ins[$ins_name];
    }

    /**
     * Construct
     * @param string $ins_name
     */
    private function __construct($ins_name)
    {
        $ins_config = LibConfig::get('redis');

        $this->host = LibCommon::getVar($ins_config, "{$ins_name}.host");
        $this->port = LibCommon::getVar($ins_config, "{$ins_name}.port");
        $this->auth = LibCommon::getVar($ins_config, "{$ins_name}.auth");
        $this->conn_type = LibCommon::getVar($ins_config, "{$ins_name}.conn_type");
    }

    /**
     * Get redis connect
     * @return object
     */
    private function & getConn() 
    {
        if(empty($this->redis)) {
            $conn_type = $this->conn_type == 'pconnect' ? 'pconnect' : 'connect';  
            !$this->select && $this->select = 0;

            $this->redis = new \Redis();
            $this->redis->$conn_type($this->host, $this->port);
            $this->auth && $this->redis->auth($this->auth);
            $this->redis->select($this->select);
        }

        return $this->redis;
    }

    /**
     * Redis method
     * @param string $func_name
     * @param array $args
     * @return mixed
     */
    public function __call($func_name, array $args = [])
    {
        $result = null;

        $redis = $this->getConn();

        if($redis && method_exists($redis, $func_name)) {
            $result = call_user_func_array([$redis, $func_name], $args);
        }

        return $result;
    }
}